package com.ubercache;

import java.util.Random;
import java.util.Set;

public class RandomStrategy implements CacheStrategy {

    private boolean remove(CacheLevel src, CacheLevel target) {

        Set<Object> keys = src.getKeys();
        
        if (keys.size() == 0) {
            return false;
        }
        
        Random r = new Random();
        int keyNum = r.nextInt(keys.size());

        Object keyToDelete = null;
        
        for (Object k : keys) {
            if (keyNum == 0) {
                keyToDelete = k;
            }
            
            keyNum--;
        }
        
        if (target != null) {
            String data = src.doGet(keyToDelete);
            
            if (data != null) {
                target.doPut(keyToDelete, data, src.getCachedEntry(keyToDelete));
            }
        }
        
        src.remove(keyToDelete);
        
        return true;
    }

    private void trim(CacheLevel src, CacheLevel target) {
        while (src.getSize() > src.getMaxSize()) {
            if (!remove(src, target)) {
                break;
            }
        }
    }
    
    @Override
    public void trimExcess(Cache cache) {
        CacheLevel level0 = cache.getLevel0();
        CacheLevel level1 = cache.getLevel1();
     
        trim(level0, level1);
        trim(level1, null);
    }

}
